// 学习记录统计模块
const LearningStats = {
    // 记录学习事件
    recordLearningEvent(isCorrect) {
        const now = new Date();
        const today = now.toISOString().split('T')[0]; // 格式：YYYY-MM-DD
        const timestamp = now.getTime();

        // 获取现有记录
        let records = localStorage.getItem('learningRecords');
        records = records ? JSON.parse(records) : {};

        // 初始化今天的记录（如果不存在）
        if (!records[today]) {
            records[today] = {
                date: today,
                totalAttempts: 0,
                correctAttempts: 0,
                totalTime: 0,
                startTime: timestamp
            };
        } else if (!records[today].startTime) {
            // 如果今天已有记录但没有开始时间，则设置开始时间
            records[today].startTime = timestamp;
        }

        // 更新记录
        records[today].totalAttempts++;
        if (isCorrect) {
            records[today].correctAttempts++;
        }

        // 计算学习时间（假设这是本次学习的结束时间）
        if (records[today].startTime) {
            const sessionTime = timestamp - records[today].startTime;
            records[today].totalTime += sessionTime;
            // 重置开始时间，以便下次记录
            records[today].startTime = timestamp;
        }

        // 保存记录
        localStorage.setItem('learningRecords', JSON.stringify(records));
    },

    // 获取指定日期范围的学习统计数据
    getStatsForDateRange(startDate, endDate) {
        let records = localStorage.getItem('learningRecords');
        records = records ? JSON.parse(records) : {};

        const stats = [];
        let currentDate = new Date(startDate);
        const end = new Date(endDate);

        while (currentDate <= end) {
            const dateStr = currentDate.toISOString().split('T')[0];
            const record = records[dateStr] || {
                date: dateStr,
                totalAttempts: 0,
                correctAttempts: 0,
                totalTime: 0
            };

            // 计算正确率
            record.accuracy = record.totalAttempts > 0 ? 
                (record.correctAttempts / record.totalAttempts) * 100 : 0;

            // 转换时间为分钟
            record.totalTimeMinutes = Math.round(record.totalTime / 60000);

            stats.push(record);

            // 移动到下一天
            currentDate.setDate(currentDate.getDate() + 1);
        }

        return stats;
    },

    // 获取最近7天的统计数据
    getRecent7DaysStats() {
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 6); // 7天前

        let stats = this.getStatsForDateRange(startDate, endDate);

        // 检查是否有数据，如果没有则添加一些模拟数据用于展示
        const hasData = stats.some(item => item.totalAttempts > 0 || item.totalTime > 0);
        if (!hasData) {
            // 生成模拟数据
            stats = stats.map(item => {
                const date = new Date(item.date);
                const dayOfWeek = date.getDay();
                
                // 工作日和周末的数据差异
                const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
                const baseTime = isWeekend ? 20 : 10;
                const baseCount = isWeekend ? 30 : 15;
                
                // 随机波动
                const time = Math.round(baseTime + Math.random() * 10);
                const count = Math.round(baseCount + Math.random() * 10);
                const correct = Math.round(count * (0.7 + Math.random() * 0.3));
                
                return {
                    date: item.date,
                    totalAttempts: count,
                    correctAttempts: correct,
                    totalTime: time * 60000, // 转换为毫秒
                    accuracy: Math.round((correct / count) * 100),
                    totalTimeMinutes: time
                };
            });
        }

        return stats;
    },

    // 绘制每天学习时间折线图
    drawTimeChart(canvasId) {
        const stats = this.getRecent7DaysStats();
        const dates = stats.map(item => item.date);
        const times = stats.map(item => item.totalTimeMinutes);

        const ctx = document.getElementById(canvasId).getContext('2d');
        
        // 使用Chart.js API获取并销毁可能存在的图表实例
        const existingChart = Chart.getChart(canvasId);
        if (existingChart) {
            //existingChart.destroy();
        }
        // 检测是否为移动设备
        const isMobile = window.innerWidth <= 768;

        // 将isMobile变量添加到图表配置对象中
        // 获取并设置canvas高度
        const chartHeight = isMobile ? 220 : 250; // 对应CSS中的高度设置
        ctx.canvas.height = chartHeight;

        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: '学习时间 (分钟)',
                    data: times,
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true
                }]
            },
            options: {
                maintainAspectRatio: false,
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '分钟'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '最近7天学习时间统计',
                        font: {
                            size: isMobile ? 14 : 16
                        }
                    }
                }
            }
        });
    },

    // 绘制每天学习数量折线图
    drawCountChart(canvasId) {
        const stats = this.getRecent7DaysStats();
        const dates = stats.map(item => item.date);
        const counts = stats.map(item => item.totalAttempts);

        const ctx = document.getElementById(canvasId).getContext('2d');
        
        // 使用Chart.js API获取并销毁可能存在的图表实例
        const existingChart = Chart.getChart(canvasId);
        if (existingChart) {
            //existingChart.destroy();
        }
        
        // 检测是否为移动设备
        const isMobile = window.innerWidth <= 768;
        // 设置canvas高度
        const chartHeight = isMobile ? 220 : 250;
        ctx.canvas.height = chartHeight;

        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: '学习数量 (题)',
                    data: counts,
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true
                }]
            },
            options: {
                maintainAspectRatio: false,
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '题目数量'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '最近7天学习数量统计',
                        font: {
                            size: 16
                        }
                    }
                }
            }
        });
    },

    // 绘制正确率折线图
    drawAccuracyChart(canvasId) {
        const stats = this.getRecent7DaysStats();
        const dates = stats.map(item => item.date);
        const accuracies = stats.map(item => item.accuracy);

        const ctx = document.getElementById(canvasId).getContext('2d');
        
        // 使用Chart.js API获取并销毁可能存在的图表实例
        const existingChart = Chart.getChart(canvasId);
        if (existingChart) {
            //existingChart.destroy();
        }
        
        // 检测是否为移动设备
        const isMobile = window.innerWidth <= 768;
        // 设置canvas高度
        const chartHeight = isMobile ? 220 : 250;
        ctx.canvas.height = chartHeight;

        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: '正确率 (%)',
                    data: accuracies,
                    backgroundColor: 'rgba(153, 102, 255, 0.2)',
                    borderColor: 'rgba(153, 102, 255, 1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true,
                    yAxisID: 'y'
                }]
            },
            options: {
                maintainAspectRatio: false,
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '正确率 (%)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '最近7天学习正确率统计',
                        font: {
                            size: 16
                        }
                    }
                }
            }
        });
    },

    // 绘制合并折线图
    drawCombinedChart(canvasId) {
        // 检测是否为移动设备
        const isMobile = window.innerWidth <= 768;

        const stats = this.getRecent7DaysStats();
        const dates = stats.map(item => item.date);
        const times = stats.map(item => item.totalTimeMinutes);
        const counts = stats.map(item => item.totalAttempts);
        const accuracies = stats.map(item => item.accuracy);

        const ctx = document.getElementById(canvasId).getContext('2d');
        
        // 使用Chart.js API获取并销毁可能存在的图表实例
        const existingChart = Chart.getChart(canvasId);
        if (existingChart) {
            //existingChart.destroy();
        }
        
        // 设置canvas高度
        const chartHeight = isMobile ? 220 : 250;
        ctx.canvas.height = chartHeight;
        
        // 创建渐变背景 - 使用设置的高度
        const canvasHeight = chartHeight;
        const timeGradient = ctx.createLinearGradient(0, 0, 0, canvasHeight);
        timeGradient.addColorStop(0, 'rgba(16, 185, 129, 0.4)');
        timeGradient.addColorStop(1, 'rgba(16, 185, 129, 0.05)');

        const countGradient = ctx.createLinearGradient(0, 0, 0, canvasHeight);
        countGradient.addColorStop(0, 'rgba(59, 130, 246, 0.4)');
        countGradient.addColorStop(1, 'rgba(59, 130, 246, 0.05)');

        const accuracyGradient = ctx.createLinearGradient(0, 0, 0, canvasHeight);
        accuracyGradient.addColorStop(0, 'rgba(139, 92, 246, 0.4)');
        accuracyGradient.addColorStop(1, 'rgba(139, 92, 246, 0.05)');

        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: '学习时间 (分钟)',
                    data: times,
                    backgroundColor: timeGradient,
                    borderColor: 'rgb(16, 185, 129)',
                    borderWidth: 3,
                    tension: 0.4,
                    fill: true,
                    pointBackgroundColor: 'white',
                    pointBorderColor: 'rgb(16, 185, 129)',
                    pointBorderWidth: 2,
                    pointRadius: isMobile ? 3 : 5,
                    pointHoverRadius: isMobile ? 5 : 7,
                    yAxisID: 'y'
                }, {
                    label: '学习数量 (题)',
                    data: counts,
                    backgroundColor: countGradient,
                    borderColor: 'rgb(59, 130, 246)',
                    borderWidth: 3,
                    tension: 0.4,
                    fill: true,
                    pointBackgroundColor: 'white',
                    pointBorderColor: 'rgb(59, 130, 246)',
                    pointBorderWidth: 2,
                    pointRadius: isMobile ? 3 : 5,
                    pointHoverRadius: isMobile ? 5 : 7,
                    yAxisID: 'y1'
                }, {
                    label: '正确率 (%)',
                    data: accuracies,
                    backgroundColor: accuracyGradient,
                    borderColor: 'rgb(139, 92, 246)',
                    borderWidth: 3,
                    tension: 0.4,
                    fill: true,
                    pointBackgroundColor: 'white',
                    pointBorderColor: 'rgb(139, 92, 246)',
                    pointBorderWidth: 2,
                    pointRadius: isMobile ? 3 : 5,
                    pointHoverRadius: isMobile ? 5 : 7,
                    yAxisID: 'y2'
                }]
            },
            options: {
                maintainAspectRatio: false,
                responsive: true,
                    responsiveAnimationDuration: 1000,
                    interaction: {
                        mode: 'index',
                        intersect: false,
                    },
                    animation: {
                        duration: isMobile ? 1000 : 2000,
                        easing: 'easeOutQuart'
                    },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '学习时间 (分钟)',
                            color: 'rgb(16, 185, 129)',
                            font: {
                            size: isMobile ? 12 : 14,
                            weight: 'bold'
                        }
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)',
                            drawBorder: false
                        },
                        ticks: {
                            color: 'rgb(75, 85, 99)'
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: !isMobile, // 在移动设备上隐藏第二个Y轴
                        position: 'left',
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '学习数量 (题)'
                        },
                        grid: {
                            drawOnChartArea: false,
                        },
                    },
                    y2: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '正确率 (%)'
                        },
                        grid: {
                            drawOnChartArea: false,
                        },
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        },
                        grid: {
                            drawOnChartArea: true,
                        },
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '最近7天学习统计',
                        font: {
                            size: 16
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                if (context.parsed.y !== null) {
                                    label += context.parsed.y;
                                    if (context.datasetIndex === 2) {
                                        label += '%';
                                    }
                                }
                                return label;
                            }
                        }
                    }
                }
            }
        });
    }
};

// 导出统计模块
if (typeof module !== 'undefined' && module.exports) {
    module.exports = LearningStats;
}